using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using AutoMapper;
using hao_Model;
using hao_Dto.User;
using hao_Reppsitory.User;
using hao_Reppsitory;

namespace User.Service.Address
{
    /// <summary>
    /// 地址服务实现
    /// </summary>
    public class AddressService : IAddressService
    {
        private readonly IAddressRepository _addressRepository;
        private readonly IUserRepository _userRepository;
        private readonly IMapper _mapper;

        public AddressService(
            IAddressRepository addressRepository,
            IUserRepository userRepository,
            IMapper mapper)
        {
            _addressRepository = addressRepository;
            _userRepository = userRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 创建地址
        /// </summary>
        public async Task<AddressDto> CreateAddressAsync(Guid userId, CreateAddressDto createAddressDto)
        {
            Console.WriteLine($"调试：开始创建地址 - UserId: {userId}");
            
            // 验证用户是否存在
            var user = await _userRepository.GetByIdAsync(userId);
            if (user == null)
            {
                throw new InvalidOperationException("用户不存在");
            }

            // 验证地址数据
            await ValidateAddressAsync(createAddressDto);

            // 检查用户地址数量限制（最多20个）
            var addressCount = await GetUserAddressCountAsync(userId);
            if (addressCount >= 20)
            {
                throw new InvalidOperationException("地址数量已达上限（最多20个）");
            }

            // 如果设置为默认地址，且用户没有默认地址，或者强制设置默认
            var hasDefault = await _addressRepository.HasDefaultAddressAsync(userId);
            if (!hasDefault || createAddressDto.IsDefault)
            {
                createAddressDto.IsDefault = true;
            }

            // 创建地址实体
            var address = _mapper.Map<hao_Model.Address>(createAddressDto);
            address.Id = Guid.NewGuid();
            address.UserId = userId;  // 显式设置用户ID
            address.CreateTime = DateTime.UtcNow;
            address.Status = 1;

            Console.WriteLine($"调试：地址实体已创建 - Id: {address.Id}, UserId: {address.UserId}, ReceiverName: {address.ReceiverName}");

            // 如果设置为默认地址，需要先清除其他默认地址
            if (createAddressDto.IsDefault && hasDefault)
            {
                // 先清除该用户的所有默认地址
                var existingAddresses = await _addressRepository.GetAddressesByUserIdAsync(userId);
                foreach (var existingAddress in existingAddresses.Where(a => a.IsDefault))
                {
                    existingAddress.IsDefault = false;
                    existingAddress.UpdateTime = DateTime.UtcNow;
                    await _addressRepository.UpdateAsync(existingAddress);
                }
            }

            // 如果用户没有地址，自动设为默认
            if (!hasDefault)
            {
                address.IsDefault = true;
            }

            Console.WriteLine($"调试：准备插入地址到数据库");
            await _addressRepository.AddAsync(address);
            Console.WriteLine($"调试：地址已成功插入数据库");
            
            return _mapper.Map<AddressDto>(address);
        }

        /// <summary>
        /// 更新地址
        /// </summary>
        public async Task<bool> UpdateAddressAsync(Guid addressId, Guid userId, UpdateAddressDto updateAddressDto)
        {
            // 检查地址是否存在且属于当前用户
            var existingAddress = await _addressRepository.GetByIdAsync(addressId);
            if (existingAddress == null || existingAddress.UserId != userId || existingAddress.Status != 1)
            {
                throw new InvalidOperationException("地址不存在或无权限操作");
            }

            // 更新地址信息
            if (!string.IsNullOrWhiteSpace(updateAddressDto.ReceiverName))
                existingAddress.ReceiverName = updateAddressDto.ReceiverName;
            
            if (!string.IsNullOrWhiteSpace(updateAddressDto.ReceiverPhone))
            {
                if (!IsValidPhone(updateAddressDto.ReceiverPhone))
                    throw new InvalidOperationException("手机号格式不正确");
                existingAddress.ReceiverPhone = updateAddressDto.ReceiverPhone;
            }
            
            if (!string.IsNullOrWhiteSpace(updateAddressDto.Province))
                existingAddress.Province = updateAddressDto.Province;
            
            if (!string.IsNullOrWhiteSpace(updateAddressDto.City))
                existingAddress.City = updateAddressDto.City;
            
            if (!string.IsNullOrWhiteSpace(updateAddressDto.District))
                existingAddress.District = updateAddressDto.District;
            
            if (!string.IsNullOrWhiteSpace(updateAddressDto.DetailAddress))
                existingAddress.DetailAddress = updateAddressDto.DetailAddress;
            
            if (!string.IsNullOrWhiteSpace(updateAddressDto.PostalCode))
                existingAddress.PostalCode = updateAddressDto.PostalCode;
            
            if (!string.IsNullOrWhiteSpace(updateAddressDto.AddressLabel))
                existingAddress.AddressLabel = updateAddressDto.AddressLabel;
            
            if (updateAddressDto.Longitude.HasValue)
                existingAddress.Longitude = updateAddressDto.Longitude;
            
            if (updateAddressDto.Latitude.HasValue)
                existingAddress.Latitude = updateAddressDto.Latitude;

            existingAddress.UpdateTime = DateTime.UtcNow;

            // 处理默认地址设置
            if (updateAddressDto.IsDefault.HasValue && updateAddressDto.IsDefault.Value)
            {
                await _addressRepository.SetDefaultAddressAsync(userId, addressId);
            }

            await _addressRepository.UpdateAsync(existingAddress);
            return true;
        }

        /// <summary>
        /// 删除地址
        /// </summary>
        public async Task<bool> DeleteAddressAsync(Guid addressId, Guid userId)
        {
            // 检查地址是否存在且属于当前用户
            if (!await _addressRepository.CheckAddressOwnershipAsync(addressId, userId))
            {
                throw new InvalidOperationException("地址不存在或无权限操作");
            }

            return await _addressRepository.SoftDeleteAsync(addressId);
        }

        /// <summary>
        /// 获取地址详情
        /// </summary>
        public async Task<AddressDto> GetAddressByIdAsync(Guid addressId, Guid userId)
        {
            var address = await _addressRepository.GetByIdAsync(addressId);
            
            // 添加详细的调试日志
            if (address == null)
            {
                Console.WriteLine($"调试：地址ID {addressId} 在数据库中不存在。");
                return null;
            }
            
            Console.WriteLine($"调试：找到地址 ID={address.Id}, UserId={address.UserId}, 请求UserId={userId}, Status={address.Status}");
            
            if (address.UserId != userId)
            {
                Console.WriteLine($"调试：地址不属于当前用户 - 地址UserId: {address.UserId}, 请求UserId: {userId}");
                return null;
            }
            
            if (address.Status != 1)
            {
                Console.WriteLine($"调试：地址状态不正常 - Status: {address.Status}");
                return null;
            }

            return _mapper.Map<AddressDto>(address);
        }

        /// <summary>
        /// 获取用户地址列表
        /// </summary>
        public async Task<List<AddressDto>> GetUserAddressesAsync(Guid  userId)
        {
            var addresses = await _addressRepository.GetAddressesByUserIdAsync(userId);
            return _mapper.Map<List<AddressDto>>(addresses);
        }

        /// <summary>
        /// 获取用户默认地址
        /// </summary>
        public async Task<AddressDto> GetDefaultAddressAsync(Guid userId)
        {
            var address = await _addressRepository.GetDefaultAddressByUserIdAsync(userId);
            return address != null ? _mapper.Map<AddressDto>(address) : null;
        }

        /// <summary>
        /// 设置默认地址
        /// </summary>
        public async Task<bool> SetDefaultAddressAsync(Guid userId, Guid addressId)
        {
            // 检查地址是否存在且属于当前用户
            if (!await _addressRepository.CheckAddressOwnershipAsync(addressId, userId))
            {
                throw new InvalidOperationException("地址不存在或无权限操作");
            }

            return await _addressRepository.SetDefaultAddressAsync(userId, addressId);
        }

        /// <summary>
        /// 分页搜索地址
        /// </summary>
        public async Task<(List<AddressDto> addresses, int totalCount)> SearchAddressesAsync(AddressSearchDto searchDto)
        {
            var (addresses, totalCount) = await _addressRepository.SearchAddressesAsync(searchDto);
            var addressDtos = _mapper.Map<List<AddressDto>>(addresses);
            return (addressDtos, totalCount);
        }

        /// <summary>
        /// 批量删除地址
        /// </summary>
        public async Task<bool> BatchDeleteAddressesAsync(List<Guid> addressIds, Guid userId)
        {
            if (addressIds == null || addressIds.Count == 0)
                return false;

            // 检查所有地址是否都属于当前用户
            foreach (var addressId in addressIds)
            {
                if (!await _addressRepository.CheckAddressOwnershipAsync(addressId, userId))
                {
                    throw new InvalidOperationException($"地址 {addressId} 不存在或无权限操作");
                }
            }

            return await _addressRepository.BatchDeleteAsync(addressIds);
        }

        /// <summary>
        /// 获取地址区域统计
        /// </summary>
        public async Task<List<AddressRegionStatsDto>> GetRegionStatsAsync()
        {
            return await _addressRepository.GetRegionStatsAsync();
        }

        /// <summary>
        /// 验证地址数据
        /// </summary>
        public async Task<bool> ValidateAddressAsync(CreateAddressDto addressDto)
        {
            if (string.IsNullOrWhiteSpace(addressDto.ReceiverName))
                throw new InvalidOperationException("收货人姓名不能为空");

            if (string.IsNullOrWhiteSpace(addressDto.ReceiverPhone))
                throw new InvalidOperationException("收货人手机号不能为空");

            if (!IsValidPhone(addressDto.ReceiverPhone))
                throw new InvalidOperationException("手机号格式不正确");

            if (string.IsNullOrWhiteSpace(addressDto.Province))
                throw new InvalidOperationException("省份不能为空");

            if (string.IsNullOrWhiteSpace(addressDto.City))
                throw new InvalidOperationException("城市不能为空");

            if (string.IsNullOrWhiteSpace(addressDto.District))
                throw new InvalidOperationException("区/县不能为空");

            if (string.IsNullOrWhiteSpace(addressDto.DetailAddress))
                throw new InvalidOperationException("详细地址不能为空");

            return true;
        }

        /// <summary>
        /// 获取用户地址数量
        /// </summary>
        public async Task<int> GetUserAddressCountAsync(Guid userId)
        {
            var searchDto = new AddressSearchDto
            {
                UserId = userId,
                Status = 1,
                PageSize = 1
            };
            var (_, totalCount) = await _addressRepository.SearchAddressesAsync(searchDto);
            return totalCount;
        }

        /// <summary>
        /// 导入地址数据
        /// </summary>
        public async Task<(int successCount, int failCount, List<string> errors)> ImportAddressesAsync(List<ImportAddressDto> addresses)
        {
            var successCount = 0;
            var failCount = 0;
            var errors = new List<string>();

            foreach (var importDto in addresses)
            {
                try
                {
                    // 根据用户标识查找用户
                    var user = await FindUserByIdentifierAsync(importDto.UserIdentifier);
                    if (user == null)
                    {
                        errors.Add($"用户 {importDto.UserIdentifier} 不存在");
                        failCount++;
                        continue;
                    }

                    // 转换为创建DTO
                    var createDto = _mapper.Map<CreateAddressDto>(importDto);
                    
                    // 创建地址
                    await CreateAddressAsync(user.Id, createDto);
                    successCount++;
                }
                catch (Exception ex)
                {
                    errors.Add($"用户 {importDto.UserIdentifier}: {ex.Message}");
                    failCount++;
                }
            }

            return (successCount, failCount, errors);
        }

        /// <summary>
        /// 导出用户地址
        /// </summary>
        public async Task<List<AddressDto>> ExportUserAddressesAsync(Guid userId)
        {
            return await GetUserAddressesAsync(userId);
        }

        #region 私有方法

        /// <summary>
        /// 验证手机号格式
        /// </summary>
        private bool IsValidPhone(string phone)
        {
            if (string.IsNullOrWhiteSpace(phone)) return false;
            return Regex.IsMatch(phone, @"^1[3-9]\d{9}$");
        }

        /// <summary>
        /// 根据用户标识查找用户
        /// </summary>
        private async Task<hao_Model.User> FindUserByIdentifierAsync(string identifier)
        {
            if (string.IsNullOrWhiteSpace(identifier)) return null;

            // 先尝试按用户名查找
            var users = await _userRepository.GetAllAsync();
            var user = users.FirstOrDefault(u => u.UserName == identifier);
            
            // 如果没找到，再尝试按手机号查找
            if (user == null)
            {
                user = users.FirstOrDefault(u => u.Phone == identifier);
            }

            return user;
        }

        #endregion
    }
}